package com.vc.filter;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.Set;

@Component
public class JwtCheckFilter implements GlobalFilter, Ordered {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Value("${no.require.urls:/admin/login}")
    private Set<String> noRequireTokenUris;

    /**
     * 过滤请求
     * @param exchange 服务器Web交换对象，包含请求和响应信息
     * @param chain    网关过滤器链，用于处理后续的过滤器
     * @return Mono<Void> 返回Mono<Void>对象，表示异步操作的结果
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 1:该接口是否需要token 才能访问
        if (isRequireToken(exchange)){
            return chain.filter(exchange);// 不需要token直接放行
        }
        // 2:取出用户的token
        String token = getUserToken(exchange);
        // 3:判断用户的token 是否有效
        if (StringUtils.isEmpty(token)){
            return buildeNoAuthorizationResult(exchange);
        }
        Boolean hasKey = redisTemplate.hasKey(token);
        if (hasKey!=null && hasKey){
            return chain.filter(exchange);// 直接放行
        }
        return buildeNoAuthorizationResult(exchange);
    }

    /**
     * 构建无授权结果的方法(给用户响应一个没有token的错误)
     *
     * @param exchange ServerWebExchange对象，用于处理Web请求和响应
     * @return Mono<Void> 返回一个Mono<Void>对象，表示操作的结果
     */
    private Mono<Void> buildeNoAuthorizationResult(ServerWebExchange exchange) {
        ServerHttpResponse response = exchange.getResponse();
        response.getHeaders().set("Content-Type", "application/json;charset=UTF-8");
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("error","NO AUTHORIZATION");
        jsonObject.put("errorMsg","Token is Null or Error");
        DataBuffer wrap = response.bufferFactory().wrap(jsonObject.toJSONString().getBytes());
        return response.writeWith(Flux.just(wrap));
    }

    /**
     * 从请求头中获取用户的token
     * @param exchange
     * @return
     */
    private String getUserToken(ServerWebExchange exchange) {
        String token = exchange.getRequest().getHeaders().getFirst(HttpHeaders.AUTHORIZATION);
        return token == null ? null : token.replace("bearer","");
    }

    private boolean isRequireToken(ServerWebExchange exchange) {
        String path = exchange.getRequest().getURI().getPath();
        if (noRequireTokenUris.contains(path)){
            return false; // 不需要token
        }
        return Boolean.TRUE;
    }

    /**
     * 获取执行顺序。
     * @return 返回执行顺序，数值越小优先级越高。
     */
    @Override
    public int getOrder() {
        return 0;
    }
}
